from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from core.base.orm_model import Base


class Permission(Base):
    """权限表"""
    __tablename__ = "permissions"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, nullable=False, comment="权限名称")
    code = Column(String(50), unique=True, nullable=False, comment="权限代码")
    desc = Column(String(255), comment="权限描述")
    parent_id = Column(Integer, ForeignKey("permissions.id"), comment="父级权限ID")
    type = Column(Integer, nullable=False, default=1, comment="类型：1-菜单，2-按钮")
    path = Column(String(255), comment="路由路径")
    component = Column(String(255), comment="组件路径")
    icon = Column(String(50), comment="图标")
    sort = Column(Integer, default=0, comment="排序")
    status = Column(Boolean, default=True, comment="状态：True-启用，False-禁用")
    create_time = Column(DateTime, default=datetime.now, comment="创建时间")
    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    is_hidden = Column(Boolean, default=False, comment="是否隐藏：False-显示，True-隐藏")
    keep_alive = Column(Boolean, default=True, comment="是否缓存：False-不缓存，True-缓存")
    is_iframe = Column(Boolean, default=False, comment="是否内嵌：False-否，True-是")
    link = Column(String(255), comment="外部链接")

    # 关联关系
    parent = relationship("Permission", remote_side=[id], backref="children")
    roles = relationship("Role", secondary="role_permissions", back_populates="permissions")

    def __repr__(self):
        return f"<Permission {self.name}>"